package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.service.UserService;
import com.itheima.util.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import redis.clients.jedis.JedisPool;

import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    private JedisPool jedisPool;

    //图片上传
    @RequestMapping("/upload")
    public Result upload(@RequestParam("imgFile") MultipartFile imgFile) {
        try {
            //获取原始文件名
            String originalFilename = imgFile.getOriginalFilename();
        /*
        lastIndexOf 是从右向左查某个指定的字符串在字符串中最后一次出现的位置（也就是从后往前查）
        与indexOf区别 indexOf是查某个指定的字符串在字符串首次出现的位置（索引值） （也就是从前往后查）
        */
            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获得文件后缀名
            String suffix = originalFilename.substring(lastIndexOf);
            //使用uuid随机产生文件名称，防止同文件名覆盖
            String fileName = UUID.randomUUID().toString() + suffix;
            //将文件上传至七牛云
            QiniuUtils.upload2Qiniu(imgFile.getBytes(), fileName);
            //图片上传成功
            Result result = new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS, fileName);
            //图片上传成功以后，将图片再存入redis缓存中(set集合)
            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES, fileName);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            //上传失败
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }
    //获取当前登陆的用户的用户名
    @RequestMapping("/getUsername")
    public Result getUsername(){
        //当springSecurity完成认证后，会将当前用户信息保存到框架提供的上下文对象中
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(user!=null){
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        }
        return new Result(false,MessageConstant.GET_USERNAME_FAIL);
    }
    @PreAuthorize("hasAnyAuthority('USER_ADD')")//权限校验
    @RequestMapping("/add")
    public Result add(@RequestBody com.itheima.pojo.User user,Integer[] roleIds){
        try {
            String password = user.getPassword();
            user.setPassword(passwordEncoder.encode(password));
            userService.add(user,roleIds);
            return new Result(true,"新增用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"新增用户失败");
        }
    }

    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        try {
            PageResult pageResult=userService.findPage(queryPageBean);
            List rows = pageResult.getRows();
            for (Object row : rows) {

            }
            return pageResult;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            com.itheima.pojo.User user=userService.findById(id);
            return new Result(true,"查询用户信息成功",user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询用户信息失败");
        }
    }

    @RequestMapping("/findRoleByUserId")
    public Result findRoleByUserId(Integer id){
        try {
            List<Integer> roleIds=userService.findRoleByUserId(id);
            return new Result(true,"查询用户对应角色成功",roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"查询用户对应角色失败");
        }
    }

    @RequestMapping("/edit")
    public Result edit(Integer[] roleIds,@RequestBody com.itheima.pojo.User user){
        try {
            userService.edit(roleIds,user);
            return new Result(true,"修改用户信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"修改用户信息失败");
        }
    }
    @PreAuthorize("hasAnyAuthority('USER_DELETE')")//权限校验
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            userService.delete(id);
            return new Result(true,"删除用户成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"删除用户失败");
        }
    }

    //获取用户头像
    @RequestMapping("/getUserImg")
    public Result getUserImg(){
        //当springSecurity完成认证后，会将当前用户信息保存到框架提供的上下文对象中
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (user!=null){
            String ImgName=userService.findUserImg(user.getUsername());
            if (ImgName!=null){
                return new Result(true,"获取头像成功",ImgName);
            }
            return new Result(false,"获取头像失败");
        }
        return new Result(false,"获取头像失败");
    }
	@RequestMapping("/exchange")
    public Result exchange(@RequestBody Map map){
        //当springSecurity完成认证后，会将当前用户信息保存到框架提供的上下文对象中
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();


        if(user!=null){

            String password1 = (String) map.get("password");

            String password2=userService.check(user.getUsername());
            if(passwordEncoder.matches(password1,password2)){
                String password = (String) map.get("newpassword");
                System.out.println(password);
                String encode = passwordEncoder.encode(password);
                System.out.println(encode);
                userService.exchange(user.getUsername(),encode);
                return new Result(true, "修改密码成功");
            }else{
                return new Result(false,"原始密码错误");
            }

        }
        return new Result(false,"修改密码失败");

    }
}
